package top.igotcha.chapter.chapter7;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author Gotcha
 * @date 2021/3/15
 * @describe 定时任务，设置，每周周一08:00执行
 */
public class ScheduleTest {
    public static void main(String[] args) {
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //获取到周四的时间
        LocalDateTime time = now.withHour(8).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.MONDAY);
        //如果当前时间>周一08:00，应当使用下周的周一
        if (now.compareTo(time)>0){
            time = time.plusWeeks(1);
        }

        //求出下次执行到现在的时间差
        long initailDelay = Duration.between(now, time).toMillis();
        long period = 1000 * 24 * 60 * 60 * 7;
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        pool.scheduleAtFixedRate(()-> System.out.println("hello"),initailDelay,period, TimeUnit.MILLISECONDS);
    }
}
